#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import time
import random
import tornado.ioloop
import tornado.locale
import tornado.web
import ConfigParser
from dbmodel import *
from interface import *

def singlerServerCheck(_service_name, _check_url, _project_id):
    from urllib2 import urlopen
    try:
        if len(_check_url) > 10:
            try:
                _get_head = urlopen("%s" % _check_url, timeout=8).getcode()
            except:
		if _check_url[-1] == "/":
                    _get_head = urlopen("%sver.txt" % _check_url, timeout=8).getcode()
                else:
                    _get_head = urlopen("%s/ver.txt" % _check_url, timeout=8).getcode()
            print type(_get_head)
        else:
            _get_head = 998
    except:
        _get_head = 999
    if _get_head == 200:
        _status = 0
    elif _get_head == 998:
        _status = 2
    elif _get_head == 999:
        _status = 9
    else:
        _status = 1
    _get_db = idb_project_url_status(_status, _project_id, _service_name)
    return


class CheckServerStatusHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _project_name = self.get_argument('s')
        if u"%s" % _project_name == u"选择项目":
            self.write(u"别瞎操作,我要崩溃了。")
            return
        _project_id = if_get_project_id(_project_name)
        _get_db = odb_project_url_info(_project_id)
        for lo in _get_db:
            singlerServerCheck(lo['servername'], lo['checkurl'], _project_id) 
        self.render("templates/returnpage.html", domain=_domain, title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/single_server/')

class SingleDoHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        try:
            _project_id = self.get_arguments('projectid')[0]
        except:
            _project_id = 0
            _context_html = "<p>参数有误</p>"
            self.write(_context_html)
            return
        try:
            _project_service = self.get_arguments('textfield')[0]
        except:
            _project_service = 0
        _new_ver = self.get_arguments('service_name')[0]
        try:
            _do = self.get_arguments('do')[0]
        except:
            _do = 0
        if (_project_id == 0) or (_project_service == 0) or (_do == 0):
            _context_html = "<p>参数有误。我要崩溃了。</p>"
            self.write(_context_html)
            return
        from interface import if_pass_decryption
        import os
        _get_db = odb_project_url_info(_project_id)
        for lo in _get_db:
            if lo['servername'] == _project_service:
                singler_service_info = lo
        _get_passwd = odb_get_service_info(_project_id, _project_service)[0]['passwd']
        _pass = if_pass_decryption(_get_passwd)
        if _do == 1:
            singlerServerCheck(singler_service_info['servername'], \
                               singler_service_info['checkurl'], \
                               _project_id)
            self.render("templates/returnpage.html", domain=_domain, title=_title, \
                                                     username = _get_user, \
                                                     items=_get_user_left_menu, \
                                                     nextpackage='/index/single_server/')
        if _do == 2:
            cmd = "python bin/commandrun.py -H %s -P %s -u %s -p %s -c \"%s\" " % \
                                                     (singler_service_info['ip'], \
                                                      singler_service_info['port'], \
                                                      singler_service_info['user'], \
                                                      _pass, \
                                                      singler_service_info['shutdown'])
            os.system(cmd)
        if _do == 3:
            cmd = "python bin/commandrun.py -H %s -P %s -u %s -p %s -c \"%s\" " % \
                                                     (singler_service_info['ip'], \
                                                      singler_service_info['port'], \
                                                      singler_service_info['user'], \
                                                      _pass, \
                                                      singler_service_info['startup'])
            os.system(cmd)
        if _do == 4:
            cmd = "python bin/commandrun.py -H %s -P %s -u %s -p %s -c \"%s\" " % \
                                                     (singler_service_info['ip'], \
                                                      singler_service_info['port'], \
                                                      singler_service_info['user'], \
                                                      _pass, \
                                                      singler_service_info['reboot'])
            os.system(cmd)
        if _do == 5:
            _local_path = "project/%s_%s" % (_project_service, _new_ver)
            cmd = "python bin/commandrun.py -H %s -P %s -u %s -p %s --localfile %s --remotefile %s" % \
                                                                                           (server_info['ip'], \
                                                                                            server_info['port'], \
                                                                                            server_info['user'], \
                                                                                            _pass, _local_path, \
                                                                                            server_info['remotepath'])
            os.system(cmd)
        self.render("templates/returnpage.html", domain=_domain, title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/single_server/')


class GetServerStatusHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _domain, _title = if_get_domain_title()
        _project_name = self.get_arguments('p')[0]
        _filter_deploy = self.get_arguments('f1')[0]
        _filter_service = self.get_arguments('f2')[0]
        if u"%s" % _project_name == u"选择项目":
            _context_html = "<p>请选择项目</p>"
            self.write(_context_html)
            return
        _project_id = if_get_project_id(_project_name)
        try:
            _get_db = odb_project_new_info(_project_name)[0]
        except:
            _context_html = u"<p>%s项目没有数据</p>" % _project_name
            self.write(_context_html)
            return
        _create_date = _get_db['create_data']
        _mark = _get_db['mark']
        if _get_db['deploy_status'] == 2:
            _html = u"ver:%s  备注:%s <font style=\"color:red\">提醒:此次部署中有error，请查看日志。</font>" % (_create_date, _mark)
        else:
            _html = u"ver:%s  备注:%s" % (_create_date, _mark)
        _online_deploy_info = odb_project_deploy_info(_project_id, \
                                                      _filter_deploy, \
                                                      _filter_service)
        for fen in _online_deploy_info:
            _service_name= fen['servername']
            _check_ver = fen['deploy_package']
            _ver_status = "%s" % fen['deploy_info']
            if _ver_status == u"0":
                _html_ver_status = u'<font style="color:green">正常</font>'
            elif _ver_status == u"1":
                _html_ver_status = u'<font style="color:red">md5验证失败</font>'
            else:
                _html_ver_status = u'<font style="color:red">未知</font>'
            _service_status = "%s" % fen['checkurl_info']
            if _service_status == u"1":
                _html_service_status = u'<font style="color:red">异常</font>'
            elif _service_status == u"0":
                _html_service_status = u'<font style="color:green">正常</font>'
            elif _service_status == u"2":
                _html_service_status = u'<font style="color:red">url有误</font>'
            else:
                _html_service_status = u'<font style="color:red">未知</font>'
            _context_html= u'''
  <form action="http://%s/index/single_server/singledo/" method="get">
    <div class="line">
        <input name="projectid" type="hidden" value="%s" />
        <input name="service_name" type="hidden" value="%s" />
        <p>
           <input name="textfield" type="text" id="textfield2" value="%s" readonly>
           <label>  当前版本:%s  </label>
           <label>  部署状态:%s  </label>
           <label>  服务状态:%s  </label>
        </p>
       <p>
          <label>
             <input type="radio" name="do" value="1" id="RadioGroup1_0">
             HTTP检查</label>
          <label>
             <input type="radio" name="do" value="2" id="RadioGroup1_1">
             停止</label>
          <label>
             <input type="radio" name="do" value="3" id="RadioGroup1_2">
             启动</label>
          <label>    
             <input type="radio" name="do" value="4" id="RadioGroup1_3">
             重启</label>
          <label>
             <input type="radio" name="do" value="5" id="RadioGroup1_4">
             重新部署不重启</label>
          <input type="submit" name="button" id="button" value="提交">
       </p>
    </div>
  </form>''' % (_domain, _project_id, _create_date, _service_name, _check_ver, \
                _html_ver_status, _html_service_status)
            _html += _context_html
        self.write(_html)

class SingleServerHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        self.render("templates/singleserver.html", domain=_domain, title=_title, \
                                                   username = _get_user, \
                                                   items=_get_user_left_menu, \
                                                   pros=_get_user_manage_project)
    def post(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _get_project_name = self.get_arguments('s')[0]
        self.render("templates/runstatus.html", domain=_domain, title=_title, \
                                                username = _get_user, \
                                                items=_get_user_left_menu)
